package com.un.ebs.core.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Description AES 加解密工具类
 * @Date 2019/2/26 17:11
 * @Created by gongxz
 */
public class AESTool {
    private static final String base = "abcdefghijklmnopqrstuvwxyz0123456789=+-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private final static String  sKey="fjkghfkjgh@#123s";
    public static String gen(int length) {

        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        return sb.toString();
    }

    // 加密
    public static String Encrypt(String sSrc) {
        byte[] encrypted = new byte[0];
        try {
            if (sKey == null) {
                System.out.println("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.println("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            //			KeyGenerator kgen = KeyGenerator.getInstance("AES");
            //	        System.out.println(sKey.getBytes().length);
            //          kgen.init(128, new SecureRandom(sKey.getBytes()));
            //          SecretKey secretKey = kgen.generateKey();
            //          byte[] raw = secretKey.getEncoded();

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); //"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return DatatypeConverter.printBase64Binary(encrypted);
        //return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    // 解密
    public static String Decrypt(String sSrc) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.println("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.println("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            //		        KeyGenerator kgen = KeyGenerator.getInstance("AES");
            //	            kgen.init(128, new SecureRandom(sKey.getBytes()));
            //	            SecretKey secretKey = kgen.generateKey();
            //	            byte[] raw = secretKey.getEncoded();

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = DatatypeConverter.parseBase64Binary(sSrc); //先用base64解密
            //byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, StandardCharsets.UTF_8);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) {
        String encrypt = AESTool.Encrypt("http://8.136.148.239/ebs-prod-api/context/");
        String decrypt = AESTool.Decrypt("+CxDj1gGD27IbGhDBNg2xohbdvDdvw/1pOZQoF92cDUJ6U9FNgX9m8BGLohU0lan2dZ8AbEIMNutAREVESQDyk3rHy/4HginNhbe9tScHT7OVw3GlikLDOcgockRvUsgXVyUSVPceOm36OM36Cffds/d/AYcILPhFZowYOxnKh/2bWczTatXW+wp5UoTfagL");
        System.out.println(encrypt);
        System.out.println(decrypt);
    }
}
